import {gameData} from "../GameData";

declare const wx: any;

class MessageCenter {
  private map: Map = new Map<string, Function>();
  private isInit = false;

  constructor() {
  }

  init() {
    if (this.isInit) {
      return;
    }
    this.isInit = true;
    wx.onMessage((msg: any) => {
      if (msg && msg.type) {
        this.emit(msg.type, msg.data)
      }
    })
  }

  on(type: string, callback: Function) {
    if (!this.map.get(type)) {
      this.map.set(type, new Set<Function>());
    }
    let handlers = this.map.get(type);
    handlers.add(callback);
  }

  private emit(type: string, data: any) {
    const handlers = this.map.get(type);
    if (!handlers) {
      return;
    }
    handlers.forEach(callback => {
      callback(data);
    })
  }

  offAll() {
    this.map = new Map();
  }
}

class SceneListener {
  private isInit = false;
  private isRank = true;

  init() {
    if (this.isInit) {
      return;
    }
    this.isInit = true;
    wx.onMessage(data => {
      switch (data.message) {
        case 'showGame':
          cc.director.loadScene('GameSubScene')
          break;
        case 'phb':
          cc.director.loadScene("pppScene");
          break;
        case 'rank':
          this.isRank = true;
          cc.director.loadScene('rankScene')
          break;
        case 'back':
          if (this.isRank) {
            cc.director.loadScene('rankScene')
          } else {
            cc.director.loadScene("phbScene");
          }
          break;
        case 'backGame':
          cc.director.loadScene("MainSub");
          break;
        case 'getData':
          gameData.postScore(data.score, data.openid);
          this.isRank = false;
          cc.director.loadScene('phbScene')
          break;
      }
    });
  }
}

export const sceneListener = new SceneListener();
export const messageCenter = new MessageCenter();